package com.msb.commons.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.msb.commons.constant.IdentityConstant;
import com.msb.commons.constant.TokenConstant;
import com.msb.commons.response.TokenResponse;
import com.msb.commons.response.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: chshh
 * @version: 1.0
 */
public class JwtUtils {
    //盐
    private static final String SIGN = "chshh@!#$";

    private static final String JWT_KEY_PHONE = "Phone";

    private static final String JWT_KEY_IDENTITY = "identity";
    //token类型
    private static final String JWT_TOKEN_TYPE = "tokenType";

    private static final String JWT_TOKEN_TIME = "tokenTime";

    //生成token
    public static String generatorToken(String passengerPhone,String identity,String tokenType){
        Map<String ,String> map = new HashMap<>();
        map.put(JWT_KEY_PHONE,passengerPhone);
        map.put(JWT_KEY_IDENTITY,identity);
        map.put(JWT_TOKEN_TYPE,tokenType);
        map.put(JWT_TOKEN_TIME,Calendar.getInstance().getTime().toString());
        //token过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1);
        Date time = instance.getTime();

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload，拉姆达表达式
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        //设置过期时间
        //builder.withExpiresAt(time);

        //生成token
        String token = builder.sign(Algorithm.HMAC256(SIGN));
        return token;
    }

    //验证token
    public static TokenResult parseToken(String token){

        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();

        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    public static void main(String[] args) {
        String s = generatorToken("15655556692", IdentityConstant.PASSENGER, TokenConstant.ACCESS_TOKEN_TYPE);
        System.out.println("生成的token: "+ s);

        System.out.println("手机号: "+parseToken(s).getPhone());
        System.out.println("身份: "+parseToken(s).getIdentity());
    }
}
